package com.imc.platform.base.category.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imc.core.utils.MysqlUtil;
import com.imc.platform.base.category.pojo.Category;
import com.imc.platform.base.category.service.ICategoryService;
import com.imc.platform.base.menu.pojo.Menu;
import com.imc.platform.base.user.pojo.User;
import com.twp.common.tuple.ResultDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;


/*
* 类描述：分类管理
* 开发者：YT
* 创建日期：2018/9/14 13:39
*/
@Slf4j
@Controller
@RequestMapping("/category")
public class CategoryController {

    public static final String imgUrl = "/images/category/";
    @Autowired
    MysqlUtil mysqlUtil;
    @Autowired
    private ICategoryService categoryService;

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class ReqTuple{
        List<String> memberList;
        String roleId;
        Map<String,String>parmsMap;
        List<Map<String,Object>> parmsList;
    }

    /*
    * YT  2018/9/14 13:44
    * 方法描述：跳转到分类管理页面
    */
    @GetMapping("/showCategoryPage")
    public String showCategoryPage(String menuId,Model model,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user=(User) session.getAttribute("currentUser");
        List<Menu> menu=categoryService.queryMenuByRoleIdAndMenuId(user.getRoleId(),menuId);
        model.addAttribute("menu",menu);
        model.addAttribute("menuId",menuId);
        return "base/category/category";
    }

    /*
    * YT  2018/9/14 22:03
    * 方法描述：跳转分类操作页面
    */
    @RequestMapping(value = "/showOperationPage",method = RequestMethod.GET)
    public String showOperationPage(@RequestParam String categoryId, Model model){
        Map<String,Object>categoryMap = new HashMap<>();
        categoryMap.put("categoryId",categoryId);
        model.addAttribute("parms",categoryMap);
        return "base/category/categoryOperation";
    }

    /*
    * YT  2018/9/14 13:49
    * 方法描述：查询分类列表
    */
    @GetMapping("/queryCategoryList")
    @ResponseBody
    public ResultDTO queryCategoryList(Pageable pageable,@RequestParam String qryCategoryName,@RequestParam String qryCategoryType){
        PageInfo<Category> queryCategoryList = categoryService.queryCategoryList(pageable.getPageNumber(),pageable.getPageSize(), qryCategoryName,qryCategoryType);
        for(Category c : queryCategoryList.getList()){
            c.setPageNumber(pageable.getPageNumber());
            c.setPageSize(pageable.getPageSize());
        }
        JSONObject map = new JSONObject();
        map.put("total",queryCategoryList.getTotal());
        map.put("rows",queryCategoryList.getList());
        map.put("pagesize",pageable.getPageSize());
        map.put("pagenumber",pageable.getPageNumber());
        ResultDTO result = ResultDTO.builder().data(map).build();
        return result;
    }

    /**
     * QY 2018/10/08 10:37
     * 方法描述：根据用户名称查询用户详情
     **/
    @RequestMapping(value = "/queryCategoryByTypeOrTypeName", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO queryCategoryByTypeOrTypeName(Pageable pageable, @RequestParam String qryCategoryName,@RequestParam String qryCategoryType) {
        PageInfo <Category> res = categoryService.queryCategoryByTypeOrTypeName(pageable.getPageNumber(), pageable.getPageSize(), qryCategoryName,qryCategoryType);
        for(Category c : res.getList()){
            c.setPageNumber(pageable.getPageNumber());
            c.setPageSize(pageable.getPageSize());
        }
        JSONObject map = new JSONObject();
        map.put("total", res.getTotal());
        map.put("rows", res.getList());
        map.put("pagesize",pageable.getPageSize());
        map.put("pagenumber",pageable.getPageNumber());
        return ResultDTO.builder()
                .data(map)
                .build();
    }

    /**
     * QY 2018/10/08 23:49
     * 方法描述：跳转查看页面
     **/
    @RequestMapping(value = "/showSCategoryPage", method = RequestMethod.GET)
    public String showSCategoryPage(@RequestParam String categoryId, Model model,String menuId) {
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("menuId",menuId);
        return "base/category/showCategory";
    }

    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转分类页面
     **/
    @RequestMapping(value = "/showCategoryPageIndex", method = RequestMethod.GET)
    public String showCategoryPageIndex() {
        return "base/category/category";
    }

    /**
     * QY 2018/9/3 17:08
     * 方法描述：根据用户id查用户
     **/
    @RequestMapping(value = "/queryCategoryById", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryCategoryById(@RequestParam String categoryId) {
        return ResultDTO.builder()
                .data(categoryService.queryCategoryById(categoryId))
                .build();
    }

    /**
     * QY 2018/10/08 10:37
     * 方法描述：跳转新增分类页
     **/
    @RequestMapping(value = "/showCategoryUpdatePage", method = RequestMethod.GET)
    public String showCategoryUpdatePage(@RequestParam String categoryId, Model model,String menuId) {
        model.addAttribute("categoryId", categoryId);
        Category itemList = categoryService.queryCategoryById(categoryId);
        model.addAttribute("itemList", itemList);
        model.addAttribute("menuId",menuId);
        return "base/category/updateCategory";
    }

    /**
     * QY 2018/10/08 10:37
     * 方法描述：跳转新增分类页
     **/
    @RequestMapping(value = "/showCategoryAddPage", method = RequestMethod.GET)
    public String showCategoryAddPage(Model model,String menuId) {
        model.addAttribute("categoryId",null);
        model.addAttribute("menuId",menuId);
        return "base/category/addCategory";
    }

    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转添加用户组织页面
     **/
    @RequestMapping(value = "/showCategoryParentNamePage", method = RequestMethod.GET)
    public String showCategoryParentNamePage(Model model) {
        return "base/category/addCategoryParentName";
    }

    /**
     * QY 2018/9/3 10:16
     * 方法描述：查询所有用户
     **/
    @RequestMapping(value = "/queryCategoryAll", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryCategoryAll(Pageable pageable,String cateType,String categoryId) {
        List<Map> queryList = categoryService.queryCategoryAll(cateType,categoryId);;
        JSONObject map = new JSONObject();
        map.put("rows", queryList);
        ResultDTO result = ResultDTO.builder().data(map).build();
        return result;
    }

    /*
     * YT  2018/9/14 19:54
     * 方法描述：新增分类
     */
    @RequestMapping(value = "/updateCategory",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO updateCategory(@RequestBody ReqTuple reqTuple){
        return ResultDTO.builder().data(categoryService.updateCategory(reqTuple.getParmsMap())).build();
    }

    /*
    * YT  2018/9/14 19:54
    * 方法描述：新增分类
    */
    @RequestMapping(value = "/addCategory",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO addCategory(@RequestBody ReqTuple reqTuple){
        List<Category> list = categoryService.queryCategoryExists(reqTuple.getParmsMap());
        if(list.size()> 0){
            //新增的分类已经存在了
            return ResultDTO.builder().data("EXISTS").build();
        }
        Map<String,String> map = reqTuple.getParmsMap();
        Category bi = new Category();
        bi.setCateName(map.get("categoryName"));
        bi.setCateType(map.get("categoryType"));
        bi.setLevel(map.get("categoryLevel"));
        bi.setParentId(map.get("parentId"));
        bi.setSn(map.get("sn"));
        categoryService.addCategory(bi);
        bi.setId(bi.getId());
        return ResultDTO.builder().data(bi).build();
    }

    /*
    * YT  2018/9/14 19:57
    * 方法描述：删除分类
    */
    @RequestMapping(value = "/delCategory",method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO delCategory (@RequestParam String id){
        return  ResultDTO.builder()
                .data(categoryService.delCategory(id))
                .build();
    }

    //绝对路径
    public String path(HttpServletRequest request){
        return accessPath+imgUrl;
    }

    @Value("${img.location}")
    String location;

    @Value("${img.accessPath}")
    String accessPath;

    //相对路径
    public String savePath(HttpServletRequest request){
        return location + imgUrl;
    }

    /**
     * 方法描述:新增bannerItem
     * SJC 2018-8-28 20:24:47
     *
     */
    @RequestMapping("/addCategoryIcon")
    @ResponseBody
    public ResultDTO addCategoryIcon(@RequestParam("file") MultipartFile file, String bnId, HttpServletRequest request) throws Exception{
        JSONObject map = new JSONObject();
        //图片模块上传多图片时候，只新增附件表。
        if (null != bnId && !"".equals(bnId)) {
            String realPath = path(request);
            String savePath = savePath(request);
            String fileName = upImg(savePath, file);

            if (null != fileName && !"".equals(fileName)) {
                map.put("reCode", "4001");
                Category bi = new Category();
                bi.setId(Integer.parseInt(bnId));
                bi.setIcon(realPath + fileName);
                int count = categoryService.updateCategoryIcon(bi);
                if (count == 0) {
                    //附件新增失败
                    map.put("reCode", "4004");
                } else {
                    map.put("reCode", "4001");
                    map.put("biId", bnId);
                    map.put("imgName", fileName);
                    map.put("imgUrl", realPath + fileName);
                }
                map.put("reCode", "4001");
                map.put("biId", bnId);
                map.put("imgName", fileName);
                map.put("imgUrl", realPath + fileName);

            } else {
                //图片上传失败
                map.put("reCode", "4002");
            }
        }
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:图片上传 返回图片路径
     * SJC 2018-8-26 16:03:21
     *
     */
    private String upImg(String savePath , MultipartFile file){

        String relFn = null;
        try {
            if(null != file){
                String filename = URLEncoder.encode(file.getOriginalFilename(), "utf-8");
                File filepath = new File(savePath,filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }

                InputStream inputStream = file.getInputStream();
                FileOutputStream fileOutputStream = null;
                String fnName = makeFileName(filename);
                relFn =fnName;
                byte[] data = new byte[1024];
                int len = 0;
                fileOutputStream = new FileOutputStream( savePath+fnName);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return relFn;
    }

    private static String makeFileName(String filename){ //2.jpg
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        // String extname = filename.substring(filename.lastIndexOf("."),filename.length());
        return UUID.randomUUID().toString() +"_"+ filename;
    }

}
